package com.edu.hre.struts.action.pim;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.entity.HrePageInfo;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.DynamicConfig;
import com.edu.hre.common.utils.ExcelProcessor;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.sql.pim.EmployeeDAOService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmployeeForm;
import com.edu.hre.struts.form.pim.EmployeeListForm;

public class EmployeeListAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(EmployeeListAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final EmployeeDAOService employeeDAOService = BeanFinder.getBean(EmployeeDAOService.BEAN_NAME, EmployeeDAOService.class);
	private final String ACTION_NAME = "employeeList";
 
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Print source code location.
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		
		String action = request.getParameter("action");
		if (action != null && "download".equals(action)) {
			
			ExcelProcessor.exportToEmployeeList(response);
			return null;
		}
		
		// Get the authorization of the current user for the specified operations. 
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);

		EmployeeListForm employeeForm = (EmployeeListForm) form;
		
		// Check if the operation is DELETE and the current user is authorized to DELETE.
		if (request.getParameter(StringConstants.BTN_DELETE) != null) {
			employeeDAOService.deleteEmployees(employeeForm);
		}
		
		// Set authorization information for the form in order to determine if the ADD or DELETE button is shown.
		employeeForm.setCanAdd(userRoleScreen.isCanCreate());
		employeeForm.setCanDelete(userRoleScreen.isCanDelete());

		// Get the sortBy parameter to determine how the result list is sorted! Then get the list and return.
		String sortBy = RequestUtils.getParameterStr(request, "sort", null);
		if (sortBy != null) { 
			employeeForm.setAsc(!employeeForm.isAsc());
			CommonUtils.sortCollection(employeeForm.getListEmployeeInfo(), employeeForm.isAsc(), sortBy);
			return mapping.findForward(ACTION_NAME);
		}

		initFormBean(employeeForm);
		
		// Paging the displaying list.
		int currentPage = RequestUtils.getParameterInt(request, "page", 1);
		int pageSize = CommonUtils.parseInt(DynamicConfig.getConfig(DynamicConfig.PAGE_SIZE), 20);
		List<EmployeeForm> listEmployeeInfo = employeeDAOService.getListEmployeeInfo(employeeForm, pageSize, pageSize * (currentPage - 1));
		int countEmp = employeeDAOService.countEmployeeInfo(employeeForm);
		
		employeeForm.setTotalPage(CommonUtils.getTotalPage(countEmp));
		employeeForm.setListEmployeeInfo(listEmployeeInfo);

		ArrayList<HrePageInfo> allPages = CommonUtils.getDisplayingPages(currentPage, CommonUtils.getTotalPage(countEmp));
		employeeForm.setListPages(allPages);
		employeeForm.setTotalItems(countEmp);

		return mapping.findForward(ACTION_NAME);
	} 
	 
	private void initFormBean(EmployeeListForm employeeForm) {

		employeeForm.setListJobTitle(ComboBoxInit.getAllJobTitles(true));
		employeeForm.setListEmploymentStatus(ComboBoxInit.getAllEmploymentStatuses(true));
		employeeForm.setListInclude(ComboBoxInit.getAllIncludeType());
		employeeForm.setListSubunit(CommonUtils.getSubunits());
	}
	
	public static void setAttributesForRequest (int empNumber, HttpServletRequest request) {
		
		HreEmployee tmp = baseService.getFirstPojo("empNumber", Compare.EQUAL, empNumber, null, null, 0, HreEmployee.class);
		
		if (tmp == null) {
			return;
		}
		
		request.setAttribute("emp_num", empNumber);
		request.setAttribute("emp_fullname", tmp.getEmpLastname() + " " + tmp.getEmpMiddleName() + " " + tmp.getEmpFirstname());
	}
	
	public static boolean isAllowedToViewEmployeeList (HreUser currentUser, int targetUserId) {
		
		if (currentUser == null) {
			return false;
		}
		
		if (currentUser.getEmpNumber() == targetUserId) {
			return true;
		}
		
		HreUserRoleScreen role = baseService.getFirstPojoAnd(new String[]{"userRoleId", "canRead", "actionName"}, new int[]{Compare.EQUAL, Compare.EQUAL, Compare.EQUAL}, 
				new Object[]{currentUser.getUserRoleId(), true, "employeeList"}, HreUserRoleScreen.class);
		
		if (role != null) {
			return true;
		}
		
		return false;
	}
}
